#include "WidgetVariantString.h"
#include "EVariant.h"
#include "WidgetVariantInt.h"
#include "ui_WidgetVariantString.h"
#include <QMetaProperty>
#include <iostream>

WidgetVariantString::WidgetVariantString(QWidget *parent) :
    WidgetVariant(parent),
    ui(new Ui::WidgetVariantString)
{
    ui->setupUi(this);
    this->buildConnect();
}

WidgetVariantString::~WidgetVariantString()
{
    // std::cout <<"delete WidgetVariantString"<< std::endl;
    delete ui;
}

void WidgetVariantString::setLabel(QString &context)
{
    ui->labelName->setText(context);
}

void WidgetVariantString::setContext(QString& context)
{
    ui->lineEdit->setText(context);
}

void WidgetVariantString::setIfReadOnly(bool boolValue)
{
    ui->lineEdit->setReadOnly(boolValue);
}

void WidgetVariantString::refreshByProperty( EItemMetaPropertyPtr p )
{
    WidgetVariant::refreshByProperty(p);
    this->clearConnect();

    EString text = p->nameCN.isEmpty() ? p->name : p->nameCN;
    if (text.left(3) == "ui_")
    {
        text.removeLeft(3);
    }
    ui->labelName->setText( text.data());

    p->getPropertyValue(p->value);
    ui->lineEdit->setText( p->value.to_EString().data() );

    ui->lineEdit->setReadOnly(p->ifReadOnly);
    if (p->ifReadOnly == true)
    {
        ui->lineEdit->setEnabled(false);
    }
    else
    {
        ui->lineEdit->setEnabled(true);
    }
    this->buildConnect();
}
    
void WidgetVariantString::buildConnect()
{
	QObject::connect(ui->lineEdit, 
                    SIGNAL(textChanged(const QString&)), 
                    this, 
                    SLOT(slotValueChanged(const QString&)));
}

void WidgetVariantString::clearConnect()
{
	QObject::disconnect(ui->lineEdit, 
                    SIGNAL(textChanged(const QString&)), 
                    this, 
                    SLOT(slotValueChanged(const QString&)));
}

void WidgetVariantString::slotValueChanged(const QString& value)
{
    EString str(value.toStdString().data());
    EVariant varOld = this->m_property->value;
    EVariant var(str);
    this->m_property->setPropertyValue(var);
    //this->m_property->value = var; 

    // m_property->value = ui->lineEdit->text().toStdString().data();
    // emit signalVariantChanged(m_property);
    emit signalVariantChanged(this->m_property, varOld);
}
